package com.ailesson.order.interceptors;

import com.ailesson.common.core.AuthContextHolder;
import com.ailesson.common.util.JwtUtil;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class UserLoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        this.initUserLoginVo(request);
        return true;
    }

    private void initUserLoginVo(HttpServletRequest request){
        String token = request.getHeader(JwtUtil.TOKEN_NAME);
        if (StringUtils.isEmpty(token)) {
            AuthContextHolder.setUserId(1L);
        } else {
            Long userId = JwtUtil.getUserId(token);
            if (StringUtils.isEmpty(userId)) {
                AuthContextHolder.setUserId(1L);
            } else {
                AuthContextHolder.setUserId(userId);
            }
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        AuthContextHolder.removeUserId();
    }
}
